#include "ColorTexture.hpp"
#include "Core/Buffer/LumineBuffer.hpp"
#include "Core/Buffer/StagingBuffer.hpp"

void Lumine::ColorTexture::createTextureImage()
{
    int texWidth, texHeight, texChannels;
    // 加载图像
    stbi_uc *pixels = stbi_load("Textures/paimon.jpg", &texWidth, &texHeight, &texChannels, STBI_rgb_alpha);
    vk::DeviceSize size = texWidth * texHeight * 4;
    if (!pixels)
    {
        throw std::runtime_error("failed to load texture image!");
    }
    // 创建buffer并把图像数据复制到buffer中
    StagingBuffer stagingBuffer;
    stagingBuffer.Create(size);
    void *data = stagingBuffer.MapMemory(size);
    memcpy(data, pixels, size);
    stagingBuffer.UnMapMemory();
    stbi_image_free(pixels);
    // 创建图像
    auto tiling = vk::ImageTiling::eOptimal;
    auto usage = vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled;
    auto properties = vk::MemoryPropertyFlagBits::eDeviceLocal;
    createImage(texWidth, texHeight, m_format, tiling, usage, properties, textureImage, m_memory);
    transitionImageLayout(textureImage, vk::ImageAspectFlagBits::eColor,vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal);
    copyBufferToImage(stagingBuffer.Buffer(), textureImage, texWidth, texHeight);

    transitionImageLayout(textureImage,vk::ImageAspectFlagBits::eColor, vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eShaderReadOnlyOptimal);
}

void Lumine::ColorTexture::Create()
{
    createTextureImage();
    LumineBuffer::createTextureImageView(m_imageView, vk::ImageAspectFlagBits::eColor, textureImage, m_format);
    LumineBuffer::createTextureSampler(m_sampler);
}